package cloud.maque.admin.impl;

import cloud.maque.admin.domain.entity.MqCombo;
import cloud.maque.admin.mapper.MqComboMapper;
import cloud.maque.admin.service.MqComboService;
import cloud.maque.admin.service.MqTenantService;
import cloud.maque.framework.common.exception.BusinessException;
import cloud.maque.framework.common.request.PaginateDataResquest;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhuyf
 * @date 2023/5/13 15:16
 */
@Service
public class MqComboServiceImpl
        extends ServiceImpl<MqComboMapper, MqCombo>
        implements MqComboService {


    @Autowired
    MqTenantService tenantService;

    @Override
    public MqCombo saveCombo(MqCombo combo) {

        if (StrUtil.isEmptyIfStr(combo.getComboName())) {
            throw new BusinessException("名称不能为空");
        }
        saveOrUpdate(combo);
        return combo;
    }

    @Override
    public Boolean deleteById(String comboId) {

        //判断该套餐是否有被其它租户使用，否则不能删除
        if (tenantService.getCountByComboId(comboId) > 0) {
            throw new BusinessException("该套餐被租户使用，不能被删除");
        }
        return removeById(comboId);
    }

    @Override
    public PageInfo<MqCombo> page(PaginateDataResquest<MqCombo> pageReq) {

        PageHelper.startPage(pageReq.getPageIndex(), pageReq.getPageSize());
        QueryWrapper<MqCombo> wrapper = new QueryWrapper<>();

        if (!StrUtil.isEmptyIfStr(pageReq.getData().getComboId())) {
            wrapper.lambda().eq(MqCombo::getComboId, pageReq.getData().getComboId());
        }

        if (!StrUtil.isEmptyIfStr(pageReq.getData().getStatu())) {
            wrapper.lambda().eq(MqCombo::getStatu, pageReq.getData().getStatu());
        }

        if (!StrUtil.isEmptyIfStr(pageReq.getData().getComboName())) {
            wrapper.lambda().like(MqCombo::getComboName, pageReq.getData().getComboName());
        }

        wrapper.lambda().orderByAsc(MqCombo::getCreateAt);
        List<MqCombo> results = this.baseMapper.selectList(wrapper);
        PageInfo<MqCombo> pageInfo = new PageInfo<MqCombo>(results);
        return pageInfo;
    }

}
